package 力扣面试经典150;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2024-03-20
 * Time:16:34
 */

/**
 * 力扣面试经典150:19. 删除链表的倒数第 N 个结点
 * 中等
 * 相关标签
 * 相关企业
 * 提示
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * 示例 1：
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 */
public class removeNthFromEnd {
    public static void main(String[] args) {
        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        ListNode d = new ListNode(4);
        ListNode e = new ListNode(5);
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;
        removeNthFromEnd(a,2);
    }
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || n <= 0) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy.next;
        ListNode cur = dummy;
        ListNode count = dummy.next;
        int num = 0;
        while(count != null){
            count = count.next;
            num++;
        }
        if(n > num) return head;
        for(int i = n;i < num;i++){
            pre = pre.next;
            cur = cur.next;
        }
        cur.next = pre.next;
        pre.next = null;
        return dummy.next;
    }
}
